// challeng/pages/wplay/wplay.js
var app = getApp();
var answerTimer = null;
Page({
	onShareAppMessage:function(){
	  var that = this;
	  var mid = that.data.mem.id;
	  var sharedata = that.data.shareData;
	  sharedata.path = 'challeng/pages/index/index?mid='+mid+'&gType=4';
	  return {
		  title: sharedata.title,
	     // desc: sharedata.desc,
	      path: sharedata.path,
	      imageUrl:sharedata.pic,
	      success(res){
	    	  var shareTicket = res.shareTickets[0] // 获取 shareTicket
	    	  wx.getShareInfo({
	              shareTicket: shareTicket,
	              complete(res) {
	            	  app.util.request({
		    	        url: 'entry/wxapp/addnums',
		    	        data: {
		    	            m : 'junsion_challeng',
		    	            t : 1,
		    	            mid : that.data.openid,
		    	            iv : res.iv,
		    	            encryptedData : res.encryptedData,
		    	        },
		    	        success: function (res) {
		    	        	if (res.data.code == 1) {
		                        that.setData({ challeng_num: parseInt(res.data.num)});
	                        	wx.showToast({
	                        		title:'次数\t+'+res.data.num,
	                        		icon:'none',
	                				mask:true,
	                				duration:1000
	                			});
		    	    	    } 
		    	        	else{
		    	        		 wx.showModal({title:res.data.msg,showCancel:false});
		    	        	}
		    	        }
		    	    }); 
	                
	              }
	          });
	      },
	      fail: function(res) {
	        // 转发失败
	    	  console.log(res);
	      }
	  }
  },
  data: {
	game_bg:'',  
	openid:'',
	gametoken:'',
	str_time:'',
  	mem:{},
  	total:0,
  	cur_num:0,
  	cur_i:0,
  	times:[],
  	g_nums:[],
	resettime:5,
	answerIng:false,
	problem:[],
	userSel:[],
	phrase_set:[false,false,false,false],
  	
  	beginCountDown: 5,//游戏开始--倒计时
    gamingStatus: 'notBegin',//游戏状态4个。notBegin未开始，running正在运行，fail挑战失败,success挑战成功
  },
  onLoad: function (options) {
	  var that = this;
	  wx.showLoading({title:'数据加载中...'});
	  app.sysInit(this,function(res){
		  app.getUserInfo(function (res) {
	      	var openid = res['openid'];
	      	//获取分享内容
	          app.getShareData(function(res){
	          	that.setData({shareData:res.data});
	          },openid,4);
	          
	      	that.setData({openid:openid});
	      	app.util.request({
			        url: 'entry/wxapp/wplay',
			        data: {
			          m: 'junsion_challeng',
			          t: 1,
			          openid:openid,
			          game:4,
			        },
			        success: function (res) {
			          wx.hideLoading();
			          if(res.data.code==0 || res.data.code==2){
			        	  var code = res.data.code;
			        	  wx.showModal({
			                  title:res.data.msg,
			                  showCancel:false,
			                  success: function(res) {
			                	  wx.showLoading({title:'数据加载中...'});
			                	  if(code==2)
			                		  var url = '../index/index?gobuy=1';
			                	  else var url = '../index/index';
			                	  wx.redirectTo({
			    	    			  url: url
			    	    		  })
			                  }
		                  });
			          }
			          else{
			        	  that.setData({
			        		  game_bg:res.data.game_bg,
			        		  gametoken:res.data.gametoken,
			        		  str_time:res.data.str_time,
			        		  mem:res.data.mem,
			        		  beginCountDown:res.data.down,
			        		  total:res.data.total,
			        		  times:res.data.times,
							  g_nums:res.data.g_nums,
			        		  problem:res.data.problem,
			        		  answerIng:false,
			        	  });
			        	  if(parseInt(res.data.times[0])>0){
							  that.setData({
								  resettime:res.data.times[0],
							  });
						  }
						  else if(parseInt(res.data.times[1])>0){
							  that.setData({
								  resettime:res.data.times[1],
							  });
						  }
						  else if(parseInt(res.data.times[2])>0){
							  that.setData({
								  resettime:res.data.times[2],
							  });
						  }
						  else{
							  that.setData({
								  resettime:5,
							  });
						  }
			        	  that.beginCountDown(res.data.down);//游戏主入口
			          }
			        },
			    });
		  });
	  });
	  var music = wx.getStorageSync('music');
      that.setData({
		  music:music.music,
		  err_music:music.err_music,
	  });
	  
  },
  onReady: function () {
	  var that=this;
  	  this.audioCtx = wx.createAudioContext('myAudio')
      this.errAudio = wx.createAudioContext('errAudio')
      this.audioCtx.play()
  },
  goAdd:function(e){
	  var that = this;
	  var dataset = e.currentTarget.dataset;
  	  var index = dataset.index;
  	  var userSel = that.data.userSel;
  	  if(userSel[index]){
  		  var phrase_set = that.data.phrase_set;
  		  var cur_num = parseInt(that.data.cur_num);
  		  var phrase = that.data.problem[cur_num].phrase;
  		  var t_index = 0;
  		  for(var jj=0;jj<phrase.length;jj++){
  			  if(phrase[jj]==userSel[index]){
  				t_index = jj;
  				break;
  			  }
  		  }
  		  phrase_set[t_index] = false;
  		  userSel[index] = '';
  		  var cur_i = parseInt(that.data.cur_i);
  		  cur_i--;
  		  that.setData({userSel:userSel,cur_i:cur_i,phrase_set:phrase_set});
  	  }
  },
  goCheck:function(e){
	  var that = this;
  	  var dataset = e.currentTarget.dataset;
  	  var index = dataset.index;
  	  var cur_num = parseInt(that.data.cur_num);
  	  var phrase = that.data.problem[cur_num].phrase;
  	  var userSel = that.data.userSel;
  	  var cur_i = parseInt(that.data.cur_i);
  	  for(var ii=0;ii<4;ii++){
		  if(!userSel[ii] || userSel[ii]==''){
			userSel[ii] = phrase[index];
			break;
		  }
	  }
  	  cur_i++;
  	  var phrase_set = that.data.phrase_set;
	  phrase_set[index] = true;
  	  that.setData({userSel:userSel,cur_i:cur_i,phrase_set:phrase_set});
  	  
  	  if(cur_i==4){
  		  if(that.data.answerIng) return false;
		  that.setData({answerIng:true});
		  clearInterval(answerTimer);//用户选择答案之后就清除定时器，防止超时失败
		  var user_anwer = '';
	  	  for(var jj=0;jj<userSel.length;jj++){
	  		user_anwer+=userSel[jj];
	  	  }
	  	var right_anwer = app.strencode(that.data.problem[cur_num].phrase1,that.data.str_time);
	  	if(right_anwer!=user_anwer){
	  		that.audioCtx.pause()
	  		app.tzfail(that,4);//挑战失败
  		}
  	  else{
  		cur_num++;
		if (cur_num == parseInt(that.data.total)) {
			app.checkReward(that,4,cur_num);//中奖了
			return false;
		}
		if(parseInt(that.data.g_nums[0])>cur_num){
			var now_times=that.data.times[0];
		}
		else if(parseInt(that.data.g_nums[1])>cur_num){
			var now_times=that.data.times[1];
		}
		else if(parseInt(that.data.g_nums[2])>cur_num){
			var now_times=that.data.times[2];
		}
		else{
			var now_times=5;
		}
		if(cur_num % 10 == 0){
			//获取新的题目
			app.util.request({
  				url: 'entry/wxapp/checkwplay',
  				data: {
  					m: 'junsion_challeng',
  					t: 1,
  					mid:that.data.mem.id,
  					str_time:that.data.str_time,
  					game:4,
  				},
  				success: function (res) {
  					if(res.data.code==1){
	  					that.setData({
	  						problem: that.data.problem.concat(res.data.problem),
	  	  	            });
	  					that.timeCountDown(now_times);
						that.setData({userSel:[],phrase_set:[false,false,false,false],cur_i:0,answerIng:false,cur_num:cur_num});
  					}
  					else{
  						wx.showModal({
  							title:res.data.msg,
  							showCancel:false,
  							success: function(res) {
  								wx.redirectTo({
  									url: '../index/index'
  								})
  							}
  						});
  					}
  				}
  			});
		}
		else{
			that.timeCountDown(now_times);
			that.setData({userSel:[],phrase_set:[false,false,false,false],cur_i:0,answerIng:false,cur_num:cur_num});
		}
  	  }
  	 }
  },
  onUnload: function(){
	  clearInterval(answerTimer);
  },
  timeCountDown:function(myTime){
  	var that=this;
  	if(answerTimer){
  		clearInterval(answerTimer);
  		that.setData({ resettime: myTime });
  	}
		answerTimer = setInterval(function () {
  		if(that.data.answerIng){
  			return false;
  		}
  		that.setData({ resettime: --myTime });
  		if (myTime <= 0) {
  			//时间到，失败
  			clearInterval(answerTimer);
  			//失败处理
  			that.audioCtx.pause()
  			app.tzfail(that,4);//挑战失败
  		}
  	}, 1000);
  	
  },
//游戏开始倒计时
  beginCountDown:function(countTime){
      var that=this;
      var timer = setInterval(function () {
          that.setData({ beginCountDown: --countTime });
          if (countTime <= 0) {
              clearInterval(timer);
              that.setData({
                  gamingStatus:'running'
              });
              that.timeCountDown(parseInt(that.data.resettime));//游戏主入口
          }
      }, 1000)
  }

})